'''
md博客修改器
'''
import datetime
import os
import time

import requests
import win32file

path="C:\\Users\\Administrator\\Desktop\\md-Blog\\md"
image_path="C:\\Users\\Administrator\\Desktop\\md-Blog\\images\\"

def delete_lines(filename, start, end):
    with open(filename, 'r') as f:
        lines = f.readlines()
    with open(filename, 'w') as f:
        for i, line in enumerate(lines):
            if i < start-1 or i >= end:
                f.write(line)

def modify_file(file_path,new_ctime, new_atime, new_mtime):
    print(file_path)
    handle = win32file.CreateFile(
        file_path,
        win32file.GENERIC_READ | win32file.GENERIC_WRITE,
        0,
        None,
        win32file.OPEN_EXISTING,
        0,
        0,
    )
    win32file.SetFileTime(handle, new_ctime, new_atime, new_mtime)  # 注意这里的顺序，访问时间在前，修改时间在后
    win32file.CloseHandle(handle)


def download_image(url, save_path):
    # 发送HTTP请求，获取图片数据
    response = requests.get(url)
    # 将图片数据保存到文件
    with open(save_path, 'wb') as f:
        f.write(response.content)

def get_seconds(str_time):
    # 将字符串时间转换为datetime对象
    datetime_obj = datetime.datetime.strptime(str_time, '%Y-%m-%d %H:%M:%S')

    # 将datetime对象转换为Unix时间戳
    return datetime_obj.timestamp()

    # 将Unix时间戳乘以1e9，得到integer nanoseconds
    #return int(unix_timestamp * 1e9)
import re

def find_image_links(text):
    # 匹配网络图片链接的正则表达式
    pattern = r'(https?://\S+\.(?:jpg|jpeg|png|gif))'
    # 查找所有匹配的图片链接
    matches = re.findall(pattern, text)
    # 提取图片地址和图片带后缀的名称
    image_links = []
    for match in matches:
        image_url = match
        image_name = match.split('/')[-1]
        image_links.append((image_url, image_name))
    return image_links

def modify_files(path):
    for file in os.listdir(path):
        if file.endswith(".md"):
            print(file)
            categroy=None
            blog_time = time.time()
            with open(os.path.join(path, file), 'r+', encoding='utf-8') as f:
                lines = f.readlines()
                if len(lines) < 15:
                    continue
                index_list=[i for i in range(15) if '---' in lines[i]]
                print(index_list)
                #
                for i in range(15):
                    if 'category:' in lines[i]:
                        index_categroy = [i, i+1 ,i+2]
                    if 'date:' in lines[i]:
                        tmp=lines[i].strip().replace('date:', '').strip()
                        print(tmp)
                        blog_time = datetime.datetime.strptime(tmp, "%Y-%m-%d %H:%M:%S")
                # index_categroy= [i for i in range(15) if 'category:' in lines[i] and ('- ' in lines[i] or '- ' in lines[i+1]) ]

                for i in index_categroy:
                    if '- ' in lines[i]:
                        categroy = lines[i].strip().replace('-', '')
                        break
                    elif '- ' in lines[i + 1]:
                        categroy = lines[i + 1].strip().replace('-', '')
                        break
                    if '- ' not in lines[i] and '- ' not in lines[i+1]:
                        categroy = lines[i].strip().replace('category:', '').strip()
                        if categroy is None:
                            categroy = lines[i+1].strip()
                        break
                if categroy:
                    categroy = categroy.strip().replace('-','')
                    print(categroy)
                if categroy and not os.path.exists(os.path.join(path, categroy)):
                    os.mkdir(os.path.join(path, categroy))

                if categroy and not os.path.exists(os.path.join(path, categroy, file)):
                    open(os.path.join(path, categroy, file), 'w').close()

                with open(os.path.join(path, categroy, file), 'w', encoding='utf-8') as f2:
                    # 写文件
                    f.seek(0)
                    f.truncate()
                    #f.writelines(lines[index_list[1]:])
                    for line in lines[index_list[1]:]:
                        if '<!-- more -->' not in line:
                            if 'http://image.windanchaos.tech/blog/' in line:
                                line = line.replace('http://image.windanchaos.tech/blog/','https://blog.windanchaos.tech/myblog/images/')
                            if 'https://testerhome.com/uploads/photo/2023/' in line:
                                image_info=find_image_links(line)
                                line = line.replace('https://testerhome.com/uploads/photo/2023/',
                                                    'https://blog.windanchaos.tech/myblog/images/').replace('!large', '').replace('![]','!['+image_info[0][1]+']')

                                print(image_info[0][0])
                                download_image(image_info[0][0],image_path+image_info[0][1])

                            f2.write(line)
                # 修改创建时间
                if os.path.exists(os.path.join(path, categroy, file)):
                    modify_file(os.path.join(path, categroy, file), blog_time, blog_time, blog_time)

modify_files(path)

